package cn.fyl.user.controller;

import cn.fyl.basic.exception.BusinessException;
import cn.fyl.basic.util.JsonResult;

import cn.fyl.basic.util.PageList;
import cn.fyl.user.domain.User;
import cn.fyl.user.dto.RegisterDto;
import cn.fyl.user.query.UserQuery;
import cn.fyl.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    public List<User> findAll(){
        return userService.loadAll();
    }

    /**
     * 查询一个
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public User findById(@PathVariable("id") Long id){
        return userService.loadById(id);
    }

    /**
     * 删除操作
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        try {
            userService.remove(id);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败");
        }
    }

    /**
     * 添加和修改操作
     * @param User
     * @return
     */
    @PostMapping
    public JsonResult save(@RequestBody User User){
        try {
            if(User.getId()==null){
                userService.save(User);
            }else {
                userService.update(User);
            }
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败");
        }

    }

    /**
     * 分页查询
     * @param
     * @return
     */
    @PutMapping
    public PageList<User> queryPage(@RequestBody UserQuery query){
        try {
            return userService.queryData(query);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageList<User>();
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    public JsonResult patchDelete(@RequestBody List<Long> ids){
        try {
            userService.patchDelete(ids);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败");
        }
    }

    /**
     * 手机号注册
     * @param dto
     * @return
     */
    @PostMapping("/phoneRegister")
    public JsonResult phoneRegister(@RequestBody RegisterDto dto){
        try {
            userService.phoneRegister(dto);
            return JsonResult.me();
        }catch (BusinessException e) {
            e.printStackTrace();
            return JsonResult.me().setMsg(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("系统异常，请稍后重试");
        }

    }
}
